import { save } from '@tauri-apps/api/dialog';
import { copyFile } from '@tauri-apps/api/fs';
import { join } from '@tauri-apps/api/path';
import { notification } from 'antd';
import React, { useContext, useEffect, useState } from 'react';
import type { MB_KEYS } from '../../constants/default';
import { FILL_TABLE_COLLECTION } from '../../constants/default';
import type { mbpz_ } from '../../lib/types/mbpz';
import type { IUploadFile } from '../../util';
import { filesPath } from '../../util';
import { FillContext } from '../app/Fill';

export interface ITplDownloadProps {
  type: MB_KEYS
}

export const TplDownload: React.FC<ITplDownloadProps> = ({ type }) => {
  const { config } = useContext(FillContext);
  const [tpl, setTpl] = useState<mbpz_[]>([]);

  useEffect(() => {
    config[FILL_TABLE_COLLECTION.EXAMPLE] && setTpl(config[FILL_TABLE_COLLECTION.EXAMPLE]);
  }, [config]);

  async function download() {
    const location = await save({
      title: '模板',
      filters: [
        {
          name: 'doc',
          extensions: ['docx', 'doc'],
        },
      ],
    });
    if (location) {
      const current = tpl.find(item => String(item.F_MBFL_) === String(type));
      console.log(current, tpl);

      if (current) {
        try {
          const attachment = JSON.parse(current.F_MBXX_)[0] as IUploadFile;
          console.log(attachment);
          // 复制模板到指定文件夹
          await copyFile(await join(await filesPath(), attachment.fileName as string) as string, location);

          notification.success({
            message: '下载完成',
          });
        }
        catch (error) {
          console.log(error);
          notification.error({
            message: '下载失败',
          });
        }
      }
    }
  }

  return (
    <a key="link" onClick={download}>模板下载</a>
  );
};
